package lex.dm.ui.actions;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import javax.swing.SwingWorker;
import javax.swing.Timer;

import org.lex.swing.ActionBuilder;

import lex.dm.DTree;
import lex.dm.loader.AbstractDataLoader;
import lex.dm.ui.ProgressDialog;

public abstract class AbstractLoadAction extends ActionBuilder {
	protected abstract AbstractDataLoader getDataLoader();

	protected abstract File getDataFile();

	public void actionPerformed( ActionEvent e )
	{
		final AbstractDataLoader loader = this.getDataLoader();
		final File file = this.getDataFile();
		final String tableName = loader.getTableName();
		final DTree app = DTree.getApplication();
		final ProgressDialog pd = new ProgressDialog( app.getRootWindow() );
		pd.setLocationRelativeTo( app.getRootWindow() );
		pd.setTitle( "Load " + tableName );
		pd.setPrompt( "Loading " + tableName + " from " + file.getName() );
		pd.setMessage( "" );
		final Timer timer = new Timer( 150, new ActionListener(){
			public void actionPerformed( ActionEvent e )
			{
				pd.setMessage( loader.getLoadedRecordCount() + " records loaded " );
			}
		} );
		timer.setInitialDelay( 0 );
		new SwingWorker<Void, Void>(){
			@Override
			protected Void doInBackground() throws Exception
			{
				System.out.println( "Start loading [" + tableName +"]");
				try
				{
					loader.load( new FileInputStream( file ) );
				}
				catch( Exception e )
				{
					System.err.println( "Loading error" );
					e.printStackTrace();
				}
				System.out.println( "[" + tableName + "] loaded" );
				return null;
			}

			@Override
			protected void done()
			{
				pd.done();
				pd.dispose();
				timer.stop();
			}
		}.execute();
		timer.start();
		pd.setVisible( true );
	}
}
